package thread;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import packageHandler.PackageHandlerForServer;
import protocol.DataPackage;
import util.DBUtil;

import com.fasterxml.jackson.databind.ObjectMapper;

public class ServerActionThread extends Thread{
	private List<String> userList;
	private ServerSocket servers;
	private Map<String, BufferedWriter> socketList;
	public ServerActionThread() {
		socketList = new HashMap<String, BufferedWriter>();			//socket表
		userList = new ArrayList<String>();												//用户列表
		Socket sockets = new Socket();
	}
	
	@Override
	public void run() {
		try {
			servers = new ServerSocket(8003);
		} catch (IOException e2) {
			e2.printStackTrace();
		}
		boolean status = true;
		while(status){
			Socket sockets = null;;
			BufferedReader readers = null;
			BufferedWriter writers = null;;
			String loginString = null;
			try {
				sockets = servers.accept();
				readers = new BufferedReader(new InputStreamReader(sockets.getInputStream()));
				writers = new BufferedWriter(new OutputStreamWriter(sockets.getOutputStream()));
				loginString = readers.readLine();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			String[] buf = loginString.split("\\\\");
			String loginName = buf[0];
			String password = buf[1];
			
			try {
				if(DBUtil.checkUser(loginName)){
					if(DBUtil.checkPasswork(loginName, password)){
						if(!DBUtil.checkIsLogin(loginName)){
							if(DBUtil.login(loginName)){
								writers.write("202\n");
								writers.flush();
								DBUtil.login(loginName);
								//成功登录
								
								String loginString1 = readers.readLine();
								ObjectMapper mapper = new ObjectMapper();
								DataPackage pack = null;
								pack = mapper.readValue(loginString1, DataPackage.class);
								//当一个用户登录，开一个线程，处理这个用户的收发信息
								new QQServerThread(socketList, userList, writers, readers, sockets).start();
							}
							else{
								writers.write("303\n");	
								writers.flush();
							}
						}
						else{
							writers.write("404\n");	//用户在线
							writers.flush();
						}
					}
					else{
						writers.write("505\n");	//用户密码
						writers.flush();
					}
				}
				else{
					writers.write("000\n");	//用户不存在
					writers.flush();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}		
		}
	}
	
}
